package com.demo.core.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.demo.core.cache.CacheKey;
import com.demo.core.cache.CacheWrapper;
import com.demo.core.dao.ConfigDao;
import com.demo.core.dao.impl.base.PageCoreDaoSupport;
import com.demo.core.model.Config;
import com.demo.core.model.support.GeneralExecuteModel;

/**
 * 配置数据访问层实现类
 * 
 * @author ryuu.kk
 */
public class ConfigDaoImpl extends PageCoreDaoSupport<Config, Long> implements ConfigDao {
	
	/**
	 * 配置空间 
	 */
	protected final static String SQLMAP_NAME_SPACE = "configSpace.";
	
	/**
	 * 数据库的表名
	 */
	protected final static String TABLE_NAME = "T_CORE_CONFIG";
	
	/**
	 * 数据库表的主键名称
	 */
	protected final static String TABLE_PK_NAME = "ID";
	
	@Override
	public int updateStatus(Config config, Map<String, Object> configStatus) {

		CacheWrapper<CacheKey, Object> cache = null;
		if (isUseCache() && (cache = getCache()) != null) {
			cache.clearAll();
		}
		
		configStatus.put("config", config);
		return getSqlMapClientTemplate().update(SQLMAP_NAME_SPACE + "changeEnabled", configStatus);
	}

	@Override
	public Config query(Long id) {
		Map<String, Object> params = new HashMap<String, Object>(3);
		params.put("id", id);
		List<Config> configList = query(params);
		return configList.size() > 0 ? configList.get(0) : null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Config> query(Map<String, Object> params) {
		
		CacheKey key = null;
		List<Config> result = null;
		CacheWrapper<CacheKey, Object> cache = null;
		
		if (isUseCache() && (cache = getCache()) != null) {
			key = new CacheKey();
			key.update(nameSpace() + "query");
			key.update(params.hashCode());
			result = (List<Config>) cache.get(key);
		}
		
		if (result == null) {
			result  = getSqlMapClientTemplate().queryForList(SQLMAP_NAME_SPACE + "queryConfig", params);
			if (isUseCache() && cache != null && result != null) {
				cache.put(key, result);
			}
		}
 		return result;
	}
	
	@Override
	protected String nameSpace() {
		return model.getNameSpace();
	}

	@Override
	protected void doInit(GeneralExecuteModel<Long> model) {
		model.setPk(TABLE_PK_NAME);
		model.setTable(TABLE_NAME);
		model.setNameSpace(SQLMAP_NAME_SPACE);
	}
}